package com.cmict.data.system.controller.admin.permission;

import cn.hutool.core.util.ObjectUtil;
import com.cmict.data.framework.common.enums.CommonStatusEnum;
import com.cmict.data.framework.common.pojo.CommonResult;
import com.cmict.data.framework.common.util.collection.SetUtils;
import com.cmict.data.framework.security.core.util.SecurityFrameworkUtils;
import com.cmict.data.system.controller.admin.auth.vo.AuthMenuRespVO;
import com.cmict.data.system.controller.admin.permission.vo.menu.*;
import com.cmict.data.system.convert.auth.AuthConvert;
import com.cmict.data.system.convert.permission.MenuConvert;
import com.cmict.data.system.dal.dataobject.permission.MenuDO;
import com.cmict.data.system.dal.dataobject.permission.UserRoleDO;
import com.cmict.data.system.dal.mysql.permission.MenuMapper;
import com.cmict.data.system.dal.mysql.permission.RoleMenuMapper;
import com.cmict.data.system.enums.permission.MenuTypeEnum;
import com.cmict.data.system.mq.producer.permission.MenuProducer;
import com.cmict.data.system.service.permission.MenuService;
import com.cmict.data.system.service.permission.PermissionService;
import com.cmict.data.system.service.permission.RoleService;
import com.cmict.data.system.service.tenant.TenantService;
import com.cmict.data.system.controller.admin.permission.vo.menu.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static com.cmict.data.framework.common.pojo.CommonResult.success;
import static com.cmict.data.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static java.util.Collections.singleton;

@Api(tags = "管理后台 - 菜单")
@RestController
@RequestMapping("/system/menu")
@Validated
public class MenuController {
    @Resource
    private MenuService menuService;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private TenantService tenantService;
    @Resource
    private MenuProducer menuProducer;
    @Resource
    private PermissionService permissionService;
    @Resource
    private RoleService roleService;

    @PostMapping("/create")
    @ApiOperation("创建菜单")
    @PreAuthorize("@ss.hasPermission('system:menu:create')")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Long> createMenu(@Valid @RequestBody MenuCreateReqVO reqVO) {
        Boolean sucess = setMenuSort(reqVO);
        Long menuId = null;
        if(sucess){
            menuId = menuService.createMenu(reqVO);
            return success(menuId);
        }
        MenuUpdateReqVO vo = new MenuUpdateReqVO();
        BeanUtils.copyProperties(reqVO,vo);
        vo.setId(menuId);
        menuService.updateMenu(vo);
        return null;
    }

    @PostMapping("/createpub")
    @ApiOperation("创建菜单")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Long> createMenuPub(@Valid @RequestBody MenuCreateReqVO reqVO) {
        Boolean sucess = setMenuSort(reqVO);
        Long menuId = null;
        if(sucess){
            menuId = menuService.createMenu(reqVO);
            return success(menuId);
        }
        MenuUpdateReqVO vo = new MenuUpdateReqVO();
        BeanUtils.copyProperties(reqVO,vo);
        vo.setId(menuId);
        menuService.updateMenu(vo);
        return null;
    }

    /**
     * 批量创建菜单
     * @param listReq
     * @return
     */
    @PostMapping("/createpubbatch")
    @ApiOperation("批量创建菜单")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<List<Long>> createMenuPubBatch(@Valid @RequestBody List<MenuCreateReqVO> listReq) {
        List<Long> result = new ArrayList<>();
        listReq.forEach(reqVO -> {
            List<MenuDO> list = menuService.getListParentId(reqVO.getParentId());
            int sort = 1;
            for (MenuDO menuDO:list) {
                if(sort!=reqVO.getSort()){
                    menuDO.setSort(sort);
                    // 更新到数据库
                    menuMapper.updateById(menuDO);
                    sort++;
                }else{
                    sort++;
                    menuDO.setSort(sort);
                    // 更新到数据库
                    menuMapper.updateById(menuDO);
                    sort++;
                }
            }
            Long menuId = menuService.createMenu(reqVO);
            result.add(menuId);
        });
        return success(result);
    }

    @PutMapping("/update")
    @ApiOperation("修改菜单")
//    @PreAuthorize("@ss.hasPermission('system:menu:update')")
    //@Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> updateMenu(@Valid @RequestBody MenuUpdateReqVO reqVO) {
        List<MenuDO> list = menuService.getListParentId(reqVO.getParentId());
        int sort = 0;
        for (MenuDO menuDO:list) {
            if(!menuDO.getId().equals(reqVO.getId())) {
                if (sort != reqVO.getSort()) {
                    menuDO.setSort(sort);
                    // 更新到数据库
                    menuMapper.updateById(menuDO);
                    sort++;
                } else {
                    sort++;
                    menuDO.setSort(sort);
                    // 更新到数据库
                    menuMapper.updateById(menuDO);
                    sort++;
                }
            }
        }
        menuService.updateMenu(reqVO);
        return success(true);
    }

    @DeleteMapping("/deletepub")
    @ApiOperation("删除菜单")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    public CommonResult<Boolean> deleteMenuPub(@RequestParam("id") Long id) {
        if(0 != id){
            List<MenuDO> list = menuService.getListParentId(id);
            if(ObjectUtil.isNotEmpty(list)){
                for (MenuDO menuDO:list) {
                    menuService.deleteMenu(menuDO.getId());
                }
            }
            menuService.deleteMenu(id);
        }
        return success(true);
    }

    @DeleteMapping("/deleteBath")
    @ApiOperation("批量删除子菜单")
    @ApiImplicitParam(name = "id", value = "编号", required= true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<Boolean> deleteBathMenu(@RequestParam("id") Long id) {
        List<MenuDO> list = menuService.getListParentId(id);
        if(ObjectUtil.isNotEmpty(list)){
            for (MenuDO menuDO:list) {
                menuService.deleteMenu(menuDO.getId());
            }
        }
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除菜单")
    @ApiImplicitParam(name = "id", value = "编号", required= true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:menu:delete')")
    public CommonResult<Boolean> deleteMenu(@RequestParam("id") Long id) {
        MenuDO menu = menuService.getMenu(id);
        menuService.deleteMenu(id);
        int sort = 0;
        List<MenuDO> list = menuService.getListParentId(menu.getParentId());
        for (MenuDO menuDO:list) {
            menuDO.setSort(sort);
            // 更新到数据库
            menuMapper.updateById(menuDO);
            sort++;
        }
        //MenuUpdateReqVO vo = new MenuUpdateReqVO();
        //BeanUtils.copyProperties(menu,vo);
        //menuService.updateMenu(vo);
        return success(true);
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取菜单列表", notes = "用于【菜单管理】界面")
    @PreAuthorize("@ss.hasPermission('system:menu:query')")
    public CommonResult<List<MenuRespVO>> getMenus(MenuListReqVO reqVO) {
        // 获得角色列表
        Set<Long> roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 获得用户拥有的菜单列表
        List<MenuDO> list = permissionService.getRoleMenuListFromCache(roleIds,reqVO);
//        List<MenuDO> list = menuService.getMenus(reqVO);
        list.sort(Comparator.comparing(MenuDO::getSort));
        return success(MenuConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/mini-list")
    @ApiOperation( "小程序获取纯表单和表单管理 菜单")
    public CommonResult<List<AuthMenuRespVO>> getMiniMenus(MenuListReqVO reqVO) {
        // 获得角色列表
        Set<Long> roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 获得用户拥有的菜单列表
        List<MenuDO> list = permissionService.getRoleMenuListFromCacheByMini(roleIds,reqVO);
//        List<MenuDO> list = menuService.getMenus(reqVO);
        list.sort(Comparator.comparing(MenuDO::getSort));
        return success(AuthConvert.INSTANCE.buildMenuTree(list));
    }
    @GetMapping("/listforform")
    @ApiOperation(value = "获取菜单列表", notes = "用于表单发布界面")
    public CommonResult<List<MenuRespVO>> getMenusForForm() {
        // 获得角色列表
        Set<Long> roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 获得用户拥有的菜单列表
        List<MenuDO> menuList = permissionService.getRoleMenuListFromCache(roleIds,
                SetUtils.asSet(MenuTypeEnum.DIR.getType(), MenuTypeEnum.MENU.getType()), // 只要目录和菜单类型
                singleton(CommonStatusEnum.ENABLE.getStatus())); // 只要开启的
        // 转换成 Tree 结构返回
        return success(MenuConvert.INSTANCE.convertList(menuList));
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取菜单精简信息列表", notes = "只包含被开启的菜单，用于【角色分配菜单】功能的选项。" +
            "在多租户的场景下，会只返回租户所在套餐有的菜单")
    public CommonResult<List<MenuSimpleRespVO>> getSimpleMenus() {
        // 获得菜单列表，只要开启状态的
        MenuListReqVO reqVO = new MenuListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        List<MenuDO> list = menuService.getTenantMenus(reqVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(MenuDO::getSort));
        return success(MenuConvert.INSTANCE.convertList02(list));
    }

    @GetMapping("/get")
    @ApiOperation("获取菜单信息")
    //@PreAuthorize("@ss.hasPermission('system:menu:query')")
    @ApiImplicitParam(name = "id", value = "编号", required= true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<MenuRespVO> getMenu(@RequestParam("id") Long id) {
        MenuDO menu = menuService.getMenu(id);
        return success(MenuConvert.INSTANCE.convert(menu));
    }

    public Boolean setMenuSort(MenuCreateReqVO reqVO) {
        List<MenuDO> list = menuService.getListParentId(reqVO.getParentId());
        int sort = 0;
        for (MenuDO menuDO:list) {
            if(sort!=reqVO.getSort()){
                menuDO.setSort(sort);
                // 更新到数据库
                menuMapper.updateById(menuDO);
                sort++;
            }else{
                sort++;
                menuDO.setSort(sort);
                // 更新到数据库
                menuMapper.updateById(menuDO);
                sort++;
            }
        }
        return true;
    }

    @GetMapping("/getsonbuttons")
    @ApiOperation(value = "获取菜单下按钮权限", notes = "获取菜单下按钮权限")
    @ApiImplicitParam(name = "parentId", value = "编号", required= true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<List<MenuRespVO>> getMenusByParentId(@RequestParam("parentId") Long parentId) {
        List<MenuDO> list = menuService.getListParentId(parentId);
        List<UserRoleDO> roleIds = permissionService.getUserRoleList(SecurityFrameworkUtils.getLoginUserId());
        Set<Long> resultSet = new HashSet();
        roleIds.forEach(roleId->{
            Set<Long> set = permissionService.getRoleMenuIds(roleId.getRoleId());
            resultSet.addAll(set);
        });
        List<MenuDO> resultList = list.stream().filter( menuDO -> resultSet.contains(menuDO.getId()))
                .collect(Collectors.toList());
        return success(MenuConvert.INSTANCE.convertList(resultList));
    }
}
